﻿@using Matrix.MaKaYunShang.Model
@using Matrix.MaKaYunShang.Model.Wechat
@model List<CardRuleBase>
    @*CardRuleBase*@
    @{
        string nonstr = JsTicket.getnonstr(16);
        double timestamp = (DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;
        ViewBag.Title = "设置卡卷发放规则";
        ViewBag.PathToBtn = "/CardRule/Index";
        ViewBag.TextBtn = "刷新";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    设置卡卷发放规则
                </div>
                <div class="panel-body">
                    <div class="row">
                        <fieldset id="content">
                            @{ int n = 0;}
                            @if(Model!=null&&Model.Any())
                            { 
                                foreach (var item in Model)
                                {
                                   
                                    <div class="col-lg-15">
                                        @{

                                            string n2 = "";
                                            n = n + 1;
                                            if (n < 10)
                                            {
                                                n2 = "0" + n.ToString();
                                            }
                                            var hidRuleDetail = "hidRuleDetail" + n2;
                                        }
                                        &nbsp;&nbsp;<span style="">时间段<lable>@n2</lable>:</span> &nbsp;&nbsp;<input type="text" value="@item.StartTime.ToString("yyyy-MM-dd")" readonly="readonly" class="form-control input-sm form_datetime_order_search" placeholder="开始时间" style="width: 150px;display: inline-block" id="dtBeginTime" name="dtBeginTime" />
                                        --
                                        <input type="text" readonly="readonly" value="@item.EndTime.ToString("yyyy-MM-dd")" class="form-control input-sm form_datetime_order_search" placeholder="结束时间" style="width: 150px; display: inline-block" id="dtEndTime" name="dtEndTime" />
                                        &nbsp;&nbsp;
                                        <input type="text" class="form-control "     style="width: 60px;display: inline-block" id='weightValue' name='weightValue' value="@item.WeightValue" />%
                                        <label style="color: red; display: ; margin-left: 5px;">已设置</label>
                                        <button id="btnSet" onclick="SetCard(this, @item.Id)" type="button" class="btn btn-primary">设置卡卷</button>
                                
                                        <input type="hidden" id="@hidRuleDetail" value="@item.RuleDetailString" />
                                        @if (n == 1)
                                        {
                                            <span>  &nbsp;&nbsp; <button id="btnAddRuleBase" type="button" class="btn btn-info">添加时间段</button></span>
                                        }
                                    </div>
                                }}
                            else
                            { 
                                <div class="col-lg-15">
                                    &nbsp;&nbsp;<span style="">时间段01:</span> &nbsp;&nbsp;<input type="text" readonly="readonly" class="form-control input-sm form_datetime_order_search" placeholder="开始时间" style="width: 150px; display: inline-block" id="dtBeginTime" name="dtBeginTime" />
                                    --
                                    <input type="text" readonly="readonly" class="form-control input-sm form_datetime_order_search" placeholder="结束时间" style="width: 150px; display: inline-block" id="dtEndTime" name="dtEndTime" />
                                    &nbsp;&nbsp;
                                    <input type="text" class="form-control " style="width: 60px;display: inline-block" id='weightValue' name='weightValue' value='100' />%
                                    <label style="color: red; display: none; margin-left: 5px;">已设置</label>
                                    <button id="btnSet" onclick="SetCard(this,0)" type="button" class="btn btn-primary">设置卡卷</button>
                                    <input type="hidden" id="hidRuleDetail01" />
                                    &nbsp;&nbsp; <button id="btnAddRuleBase" type="button" class="btn btn-info">添加时间段</button>
                                </div>
                            }
                        </fieldset>
                        <div class="col-md-12">
                            <br />
                            <button id="btnSave" type="button" class="btn btn-success">确认并保存</button>
                        </div>

                    </div>
                    
                    <div class="row" style="padding-left: 15px; padding-right: 15px; margin-top: 10px;">
                        <div class="col-lg-12">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4>新建发放规则步骤</h4>
                                </div>
                                <div class="panel-body" style="border: none">
                                    <p>1，首先点击【添加时间段】</p>
                                    <p>2，选择规则执行的时间段。</p>
                                    <p>3，填写卡券抽奖的中奖率，默认为100%，即客户扫码每次都能抽到优惠券，但抽到哪种优惠券，是根据下面的卡券数量来计算几率。</p>
                                    <p>4，设置卡券。在此时间段内可让客户抽到的卡券，则在其后面填写卡券总数量，当此时间段内某卡券的数量被抽取完了后，客户将不再能抽到此券。直到创建新的发券规则，并重新填入更多的卡券数量。</p>
                                    <p>5，规则填写完成后，点击【确认并保存】。</p>

                                    <p>
                                        温馨提示：
                                    <p>1，卡券一旦创建保存成功，暂时无法修改和删除，保存前请确认所有规则信息都是您所想的；</p>
                                    <p>2，新创建的卡券需平台审核通过后，才会在【设置卡券】里面出现；</p>
                                    <p>3，当创建一条规则完成后，卡券会一直按此规则来进行发放，如果超过了当初创建的截止时间，但又没有新的规则，则此规则会一直继续延用，直到创建了其他新的规则为止；</p>
                                    <p>4，当有多条卡券发放规则，且规则时间跨度有重复的时候，平台会按最新的一条发放规则来执行。</p>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="ChangeCardModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="max-width: 700px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">设置此时间段的卡卷</h4>
                </div>
                <div class="modal-body">

                    <div class="table-responsive table-bordered" style="max-height: 550px;">
                        @{
                            var cloudCardsList = ViewBag.CloudCardsList as List<CloudCards>;
                            if (cloudCardsList != null && cloudCardsList.Count > 0)
                            {
                                <table>
                                    <tr><th style="text-align: center">卡券名称</th><th style="text-align: center">参加此时间段的数量（不参加请填0）</th></tr>
                                    @foreach (var item in cloudCardsList)
{
    <tr id="cloudCards_@item.Id">
        <td style="padding: 5px;"><span class="input-group-addon" style="width: 295px; height: 30px; border: 1px solid #cccccc">@item.CardName</span></td>
        <td style="padding: 5px;"><input type="text" class="form-control" value="0" id="cardscount@(item.Id)" cardsid="@item.Id" style="width: 260px;" maxlength="8" /></td>
    </tr>
}
                                    <tr>
                                        <td style="padding: 5px;"><input type="hidden" id="hidNowRuleDetail" /></td>
                                        <td style="padding: 5px;"><button id="btnSaveCards" type="button" class="btn btn-success btn-main" style="float: right">确定</button></td>
                                    </tr>
                                </table>
                            }
                            else
                            {
                                <div style="text-align: center;color:red;font-size: 18px;">暂无卡券，请先添加卡券</div>
                            }
                        }
                        <input type="hidden" id="hidConsumerId" />
                        <input type="hidden" id="hidIsSetDefaultShop" />
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="/Content/admin/bower_components/jquery/dist/jquery.min.js"></script>
    <script src="/Content/alertify-js/js/alertify.js"></script>
    <script type="text/javascript">
        var n = 1;
        $(function () {
            $(".form_datetime_order_search").datetimepicker({
                format: 'yyyy-mm-dd',
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: false,
                autoclose: 1,
                todayHighlight: false,
                startView: 2,
                minView: 2,
                forceParse: 0,
                todayButton: true, startDate: new Date(new Date().setDate(new Date().getDate()))
            });

            //添加单元格
            $("#btnAddRuleBase").click(function () {
                var indexes = $("#content").children().last().find("lable").html();
                if (parseInt(indexes) > 0) {
                    n = indexes;
                }
                n++;
                if (n < 10) {
                    n = "0" + n;
                }
                var s = "RuleBase" + n + "";
                var text = "";
                text += " <div class='col-lg-15' id='RuleBase" + n + "'> ";
                text += "  &nbsp;&nbsp;<span style='width:100px'>时间段" + n + ":</span> &nbsp;&nbsp;<input type='text'  readonly='readonly'   class='form-control input-sm form_datetime_order_search' placeholder='开始时间' style='width: 150px;display: inline-block' id='dtBeginTime' name='dtBeginTime' />";
                text += " --&nbsp";
                text += "<input type='text' readonly='readonly'  class='form-control input-sm form_datetime_order_search'' placeholder='结束时间'' style='width: 150px;display: inline-block'' id='dtEndTime'' name='dtEndTime'' />";
                text += " &nbsp;&nbsp; <input type='text' class='form-control'' style='width: 60px;display: inline-block' id='weightValue' name='weightValue' value='100' />%";
                text += " <button id=''' type='button'' onclick='SetCard(this,0)' class='btn btn-primary'>设置卡卷</button> <input type='hidden' id='hidRuleDetail" + n + "' />";
                text += ' &nbsp;&nbsp; <button id="btnRemove' + n + '" onclick="btnRemove(' + s + ')" type="button" class="btn btn-danger">删除</button> </div>';
                $("#content").append(text);
            });
            //保存设置卡券
            $("#btnSaveCards").click(function () {
                var cardsJson = eval('([])');
                var isCardsCountError = false;
                $("input[cardsid]").each(function () {
                    var val = $(this).val();
                    if (!/^[-]{0,1}[0-9]{1,}$/.test(val)) {
                        isCardsCountError = true;
                    }
                    if (parseInt($(this).val()) > 0) {
                        var subCards = {
                            CloudCardId: $(this).attr("cardsid"),
                            CardTotalQuantity: $(this).val()
                        };
                        cardsJson.push(subCards);
                    }
                });
                if (isCardsCountError) {
                    alertify.alert('卡券数量只能为整数！');
                    return false;
                }
                if (cardsJson.length == 0) {
                    alertify.alert('请至少选择一样卡券！');
                    return false;  
                }
              
                $("#" + $("#hidNowRuleDetail").val()).val(JSON.stringify(cardsJson));
                $("#" + $("#hidNowRuleDetail").val()).siblings("label").show();
                $("input[cardsid]").val("0");
                $("#ChangeCardModal").modal('hide');
            });
            //保存按钮事件
            $('#btnSave').click(function () {
                var rulebase = eval('([])');
                //时间段
                var isWeightValueError = false;
                var isRuleDetailError = false;
                var isCardError = false;
                $(".col-lg-15").each(function () {
                    var startTime = $("input:eq(0)", $(this)).val();
                    var endTime = $("input:eq(1)", $(this)).val();
                    var weightValue = $("input:eq(2)", $(this)).val();
                    var ruledetail = $("input:eq(3)", $(this)).val();
                    if (startTime == "" || endTime == "") {
                        isRuleDetailError = true;
                    }
                    else if (!/^[0-9]*[1-9][0-9]*$/.test(weightValue) || weightValue < 1 || weightValue > 100) {
                        isWeightValueError = true;
                    }
                    if (ruledetail != "") {
                        var subRuleBase = {
                            Id: 0,
                            StartTime: startTime,
                            EndTime: endTime,
                            WeightValue: weightValue,
                            RuleDetailList: eval("(" + ruledetail + ")")
                        };
                        rulebase.push(subRuleBase);
                    } else {
                        isCardError = true;
                    }
                });
          
                if (isRuleDetailError) {
                    alertify.alert('有未设置卡券的时间段！');
                    return false;
                }
                if (isWeightValueError) {
                    alertify.alert('所有权重只能为1-100之间的正整数！');
                    return false;
                }
                if (isCardError) {
                    alertify.alert('请添加卡卷！');
                    return false;
                }
                if (rulebase.length == 0) {
                    alertify.alert('请至少设置一个时间段！');
                    return false;
                }
                $.ajax({
                    type: 'post',
                    url: '/CardRule/SaveCardRule',
                    data: { modelStr: JSON.stringify(rulebase) },
                    success: function (data) {
                        if (data.Status) {
                            alertify.alert('数据保存成功！');
                            window.location.reload();
                        } else {
                            alertify.alert(data.Message);
                        }
                    }
                });
            });

        });

        //移除单元格
        function btnRemove(t) {
            alertify.okBtn("确定").cancelBtn("取消").confirm("确定删除吗？删除后不可恢复", function () {
                $(t).remove();
            }, false);

        }
        //动态事件
        $("body").delegate(".form_datetime_order_search", "focusin", function () {
            $(this).datetimepicker({
                format: 'yyyy-mm-dd',
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
                , startDate: new Date(new Date().setDate(new Date().getDate() ))
            });
        });
        function SetCard(t, cardRuleBaseId) {
            $(".modal-body").find("input", $(this)).val(0);
            $("#cardscount1").val(0);
            $("#cardscount3").val(0);
            var startTime = $(t).parent().find("input:eq(0)", $(this)).val();
            var endTime = $(t).parent().find("input:eq(1)", $(this)).val();
            var weightValue = $(t).parent().find("input:eq(2)", $(this)).val();
     
            if (startTime == "" || endTime == "") {
                return alertify.alert('请先设置该时间段！');
            }
            else if (Date.parse(startTime) > Date.parse(endTime)) {
                return alertify.alert('开始时间不能大于结束时间！');
            }
            else if (!/^[0-9]*[1-9][0-9]*$/.test(weightValue) || weightValue < 1 || weightValue > 100) {
                return alertify.alert('权重值只能是1-100之间的整数');
            }
            else {
           
                if (parseInt(n) < 10) {
                    n = "0" + parseInt(n);
                }
                $("#hidNowRuleDetail").val("hidRuleDetail" + n);
                $("#ChangeCardModal").modal('show');
                $("#CardData").html("");
           
                if (cardRuleBaseId > 0 && cardRuleBaseId != null) {
                    $("#btnSaveCards").hide();
                 
                    $.post("@Url.Action("GetCardsUseCount", "CardRule")", { cardRuleBaseId: cardRuleBaseId }, function(data) {
                        if (data.Status) {
                            if (data.Data != null) {
                                for (var k = 0; k < data.Data.length; k++) {
                                    $("#cloudCards_" + data.Data[k].CloudCardId).find("input:eq(0)", $(this)).val(data.Data[k].CardTotalQuantity + "（已使用数量：" + data.Data[k].CardSendQuantity + "）");
                                }
                            }
                        }
                    });
                } else {
                    $("#btnSaveCards").show();
                }
            }
        }
    </script>
